package com.szml.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szml.constants.ImageConstants;
import com.szml.dto.LoginFormDTO;
import com.szml.mapper.UserMapper;
import com.szml.entity.User;
import com.szml.result.Result;
import com.szml.service.UserService;
import com.szml.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.szml.constants.RedisConstants.LOGIN_USER_KEY;
import static com.szml.constants.RedisConstants.LOGIN_USER_TTL;

/**
* @author 25650
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-06-17 16:08:37
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    //登录方法的实现
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.获取emil和password的值
        String email = loginForm.getEmail();
        //解密
        String password =DigestUtils.md5DigestAsHex( loginForm.getPassword().getBytes());

        //2.获取用户（查询数据库）
        User user = query().eq("email", email).one();
        //3.判断用户是否存在
        if (user==null)
        {
            //返回错误信息：用户不存在
            return Result.error("当前用户不存在");
        }
        //4.判断密码是否正确
        if (!(user.getPassword().equals(password)))
        {
            return Result.error("密码错误");
        }
        log.info("{}登录成功！",user.getUserId());
        //5.保存用户到redis
        //生成token作为令牌
        String token = UUID.randomUUID().toString(true);
        //将loginVO对象存储到redishash对象
        LoginVO loginVO = new LoginVO();
        loginVO.setUserId(user.getUserId());
        loginVO.setEmail(user.getEmail());
        loginVO.setName(user.getName());
        loginVO.setRole(user.getRole());
        loginVO.setIcon(user.getIcon());
        loginVO.setToken(token);
        CopyOptions copyOptions = CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> {
                    return fieldValue != null ? fieldValue.toString() : null;
                });

        Map<String, Object> loginvomap = BeanUtil.beanToMap(loginVO, new HashMap<>(), copyOptions);
        String tokenkey=LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenkey,loginvomap);
        //设置token有效期
        stringRedisTemplate.expire(tokenkey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.success(loginVO);
    }
    /**
     * 注册方法的实现
     * **/
    @Override
    public Result register(User user, HttpSession session) {
        User userselect=query().eq("email",user.getEmail()).one();
        //1.如果用户已存在就返回错误信息：用户已存在
        if (userselect!=null)
        {
            return Result.error("用户已存在");
        }
        //注册默认是小二，role=0，icon=默认值
        user.setRole(0);
        user.setIcon(ImageConstants.DEFAULT_ICON);
        //md5加密 密码
        String password= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);
        save(user);
        return Result.success();
    }
}




